import {State} from './state.js';

export class Klotski {
  constructor(m) {
    this.start = new State()
    for (let k of m.keys()) {
      this.start.set_coord(k, m.get(k).x,  m.get(k).y)
    }
  }

  get_result() {
    let queue = new Array()
    let visited = new Set()
    visited.add(this.start.key())
    queue.push(this.start)
    let finish = null
    while (queue.length > 0) {
      let current = queue.shift()
      if (current.success()) {
        finish = current
        break
      } else {
        let nextList = current.next()
        if (nextList.length == 0) {
          continue
        }
        for (let a of nextList) {
          let key = a.key()
          if (!visited.has(key)) {
            queue.push(a)
            visited.add(key)
          }
        }
      }
    }
    if (finish == null) {
      return null
    }
    let result = new Array()
    while (finish != null) {
      result.unshift(finish)
      finish = finish.pre
    }
    return result
  }
}